<template>
  <div class="JADP-common-layout">
    <!-- <el-tree
        :data="treeList"
        :props="defaultProps"
        default-expand-all
        highlight-current
        ref="treeBox"
        :expand-on-click-node="false"
        @node-click="handleNodeClick"
        class="JADP-common-el-tree"
        node-key="id"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <i :class="data.icon"></i>
          <span class="text">{{ node.label }}</span>
        </span>
      </el-tree> -->

    <div class="JADP-common-layout-center">
      <el-row class="JADP-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <!-- <el-col :span="6">
            <el-form-item label="课程分类">
              <el-select
                v-model="query.crmclassification"
                placeholder="请选择"
                clearable
              >
                <el-option
                  v-for="(item, index) in crmclassificationOptions"
                  :key="index"
                  :label="item.fullName"
                  :value="item.id"
                  :disabled="item.disabled"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="课程名称">
              <el-input v-model="query.crmname" placeholder="请输入" clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()"
                >查询</el-button
              >
              <el-button icon="el-icon-refresh-right" @click="reset()"
                >重置</el-button
              >
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div class="JADP-common-layout-main JADP-flex-main">
        <div class="JADP-common-head">
          <div>
            <el-button
              type="primary"
              icon="el-icon-plus"
              @click="addOrUpdateHandle()"
              >新增
            </el-button>
            <el-button type="text" icon="el-icon-download" @click="exportData()"
              >导出
            </el-button>
            <el-button
              type="text"
              icon="el-icon-delete"
              @click="handleBatchRemoveDel()"
              >批量删除
            </el-button>
          </div>
          <div class="JADP-common-head-right">
            <el-tooltip effect="dark" content="刷新" placement="top">
              <el-link
                icon="icon-ym icon-ym-Refresh JADP-common-head-icon"
                :underline="false"
                @click="reset()"
              />
            </el-tooltip>
            <screenfull :isContainer="true" />
            <el-tooltip effect="dark" content="列设置" placement="top">
              <el-link
                icon="icon-ym icon-ym-options JADP-common-head-icon"
                :underline="false"
              />
            </el-tooltip>
          </div>
        </div>
        <div class="content">
          <el-col :span="6" class="tree">
            <div class="tree-content">
              <p>课程分类</p>
              <el-tree
                :data="treeList"
                node-key="id"
                ref="tree"
                default-expand-all
                :expand-on-click-node="false"
                @node-click="treeSearch"
                :props="defaultProps"
                @node-expand="handleNodeExpand"
              >
                <template #default="{ node, data }">
                  <span class="handle-tree">
                    <el-input
                      @click.stop.native=""
                      class="add-input"
                      :value="data.label"
                      @input="(a) => inp(a, data)"
                      @focus="focus($event)"
                      v-if="data.text == '添加'"
                      @keydown.stop.native.enter="determine(data)"
                    ></el-input>
                    <span v-if="!data.text" style="font-size: 12px">{{
                      data.label
                    }}</span>
                    <span class="btns">
                      <el-button
                        v-if="data.text !== data.parentId && editLog"
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click.stop="edit(data, node)"
                      ></el-button>
                      <el-button
                        v-if="data.text !== '添加'"
                        size="mini"
                        type="text"
                        icon="el-icon-plus"
                        @click.stop="testPaper(data)"
                      ></el-button>
                      <el-button
                        v-if="data.text == '添加'"
                        icon="el-icon-check"
                        size="mini"
                        type="text"
                        @click.stop="determine(data)"
                      ></el-button>
                      <el-button
                        v-if="data.id != -1"
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click.stop="removeTree(data)"
                      ></el-button>
                    </span>
                  </span>
                </template>
              </el-tree>
            </div>
          </el-col>
          <el-col :span="18">
            <JADP-table
              v-loading="listLoading"
              :data="list"
              @sort-change="sortChange"
              has-c
              @selection-change="handleSelectionChange"
            >
              <el-table-column
                prop="crmname"
                label="课程名称"
                align="left"
                show-overflow-tooltip
              />

              <el-table-column
                label="课程分类"
                prop="crmclassification"
                algin="left"
              >
                <template slot-scope="scope">
                  <!-- {{ getDict("kjfl", scope.row.crmclassification) }} -->
                  {{ scope.row.crmclassification }}
                </template>
              </el-table-column>
              <!-- <el-table-column
                prop="crmstarttime"
                label="开始时间"
                align="left"
              />
              <el-table-column
                prop="crmendtime"
                label="结束时间"
                align="left"
              /> -->
              <el-table-column
                prop="teacher"
                label="主讲老师"
                align="left"
                show-overflow-tooltip
              />
              <!-- <el-table-column prop="teacher" label="主讲老师" align="left">
                <template #default="{ row }">
                  <ShowAllText :row="row.teacher" :num="15" />
                </template>
              </el-table-column> -->
              <!-- <el-table-column
                prop="creatortime"
                label="创建时间"
                align="left"
              />
              <el-table-column
                prop="lastmodifytime"
                label="修改时间"
                align="left"
              /> -->
              <el-table-column prop="hours" label="学时" align="left" />
              <!-- <el-table-column prop="creatoruserid" label="创建用户" align="left" /> -->
              <el-table-column label="操作" fixed="right" width="200">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    @click="addOrUpdateHandle(scope.row.id)"
                    >编辑
                  </el-button>
                  <el-button type="text" @click="practice(scope.row.id)"
                    >练习
                  </el-button>
                  <el-button
                    type="text"
                    @click="addOrUpdateHandle(scope.row.id, undefined, true)"
                    >课件列表
                  </el-button>
                  <el-button
                    type="text"
                    class="JADP-table-delBtn"
                    @click="handleDel(scope.row.id)"
                    >删除
                  </el-button>
                  <!-- <el-dropdown
                    @command="bmRecord"
                    trigger="click"
                    placement="bottom"
                  >
                    <span class="el-dropdown-link"
                      >更多<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <el-dropdown-menu slot="dropdown">
                      <el-dropdown-item
                        :command="{
                          name: 'a',
                          id: scope.row.id
                        }"
                        >课件列表</el-dropdown-item
                      >
                      <el-dropdown-item
                        :command="{
                          name: 'b',
                          id: scope.row.id,
                          manageid: scope.row.pjmanageid
                        }"
                      >
                        课程评价
                      </el-dropdown-item>
                      <el-dropdown-item
                        :command="{
                          name: 'c',
                          id: scope.row.id
                        }"
                      >
                        <el-button type="text" class="JADP-table-delBtn"
                          >删除
                        </el-button>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </el-dropdown> -->
                </template>
              </el-table-column>
            </JADP-table>
            <pagination
              :total="total"
              :page.sync="listQuery.currentPage"
              :limit.sync="listQuery.pageSize"
              @pagination="initData"
            />
          </el-col>
        </div>
      </div>
    </div>
    <JADP-Form v-if="formVisible" ref="JADPForm" @refresh="refresh" />
    <ExportBox v-if="exportBoxVisible" ref="ExportBox" @download="download" />
    <ImportBox
      v-if="importBoxVisible"
      ref="importBox"
      @refresh="reset()"
      @ImportPreviewApi="ImportPreviewApi"
      @importDataApi="importDataApi"
      @TemplateDownload="TemplateDownload"
      :URL="URL"
    />
    <Practice v-if="practiceVisible" ref="Practice" @refresh="refresh" />
    <Evaluation
      ref="Evaluation"
      v-if="evaluationVisible"
      @refresh="refresh"
      categore="59c767291601498b9b584a8fc09ab833"
      :categoretype="2"
    />
  </div>
</template>

<script>
import request from "@/utils/request";
import { getDictionaryDataSelector } from "@/api/systemData/dictionary";
import JADPForm from "./Form";
import ExportBox from "./ExportBox";
import Practice from "./practice/index.vue";
import { previewDataInterface } from "@/api/systemData/dataInterface";
import Evaluation from "../xy_ks_banjiguanli/pingjia/evaluation.vue";
export default {
  components: { JADPForm, ExportBox, Practice, Evaluation },
  data() {
    return {
      editLog: true,
      //导入属性
      importBoxVisible: false,
      URL: "courseinformation/Xy_ks_curriculum_first",
      treeList: [],
      query: {
        crmclassification: "",
        crmname: "",
      },
      defaultProps: {
        children: "children",
        label: "fullName",
      },
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "",
      },
      formVisible: false,
      exportBoxVisible: false,
      practiceVisible: false,
      evaluationVisible: false,
      columnList: [
        { prop: "creatortime", label: "创建时间" },
        { prop: "lastmodifytime", label: "修改时间" },
        { prop: "creatoruserid", label: "创建用户" },
        { prop: "crmname", label: "课程名称" },
        { prop: "crmclassification", label: "课程分类" },
        { prop: "crmstarttime", label: "开始时间" },
        { prop: "crmendtime", label: "结束时间" },
      ],
      crmclassificationOptions: [
        { fullName: "选项一", id: "1" },
        { fullName: "选项二", id: "2" },
      ],
      crmclassificationOptions: [
        { fullName: "选项一", id: "1" },
        { fullName: "选项二", id: "2" },
      ],
    };
  },
  computed: {},
  created() {
    this.initData();
    this.testPaper();
  },
  methods: {
    async edit(val, node) {
      this.$set(val, "text", "添加");
      this.$set(val, "text1", "编辑");
      this.$refs.tree.updateKeyChildren(
        val.parentId,
        JSON.parse(JSON.stringify(node.parent.data.children))
      );
    },
    focus(event) {
      event.currentTarget.select();
    },
    async determine(data) {
      if (!data.label) return this.$message.error("请先填写菜单名");
      data.typeName = data.label;
      data.organizeId = this.$store.getters.organizeId;

      if (data.text1) {
        request({
          url: "/api/xy_ks_course_type/Xy_ks_course_type/" + data.id,
          method: "PUT",
          data,
        }).then(() => {
          this.$message({
            type: "success",
            message: "修改成功！",
            duration: 500,
            onClose: () => {
              this.testPaper();
              this.initData();
              this.editLog = true;
            },
          });
        });
      } else {
        request({
          url: "/api/xy_ks_course_type/Xy_ks_course_type",
          method: "post",
          data,
        }).then(() => {
          this.$message({
            type: "success",
            message: "新建节点成功!",
            duration: 500,
            onClose: () => {
              this.testPaper();
              this.initData();
              this.editLog = true;
            },
          });
        });
      }
    },
    inp(value, data) {
      this.$set(data, "label", value);
      this.$forceUpdate();
    },
    removeTree(data) {
      let tip = "children" in data;
      if (tip && data.children)
        return this.$message.error("有子节点不可直接删除！");
      this.$confirm("确认删除节点吗？", "提示", { type: "waring" })
        .then(async () => {
          request({
            url: `/api/xy_ks_course_type/Xy_ks_course_type/${data.id}`,
            method: "DELETE",
          }).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.testPaper();
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },
    handleNodeExpand(data, node) {
      // 处理数据可以再修改的手段
      this.$refs.tree.updateKeyChildren(
        node.data.id,
        JSON.parse(JSON.stringify(node.data.children))
      );
    },
    testPaper(data) {
      this.request({
        url: "api/xy_ks_course_type/Xy_ks_course_type/getAllList",
        method: "get",
      }).then((res) => {
        this.treeList = res.data;
        let tree = {
          label: "课程分类",
          hasChildren: true,
          id: "-1",
          children: [],
        };
        if (data) {
          this.editLog = false;
          if (data.id == -1) {
            this.treeList.push({
              text: "添加",
              parentId: -1,
            });
          } else {
            this.treeList.push({
              text: "添加",
              parentId: data.id,
            });
          }
        }
        this.treeList.forEach((item) => {
          item.label = item.typeName;
          if (item.parentId == "默认") item.parentId = -1;
        });
        let parent = this.treeList.filter((item) => item.parentId == -1);
        let children = this.treeList.filter((item) => item.parentId !== -1);
        function getTreeData(parent, children) {
          parent.forEach((item) => {
            children.forEach((item1) => {
              if (item1.parentId == item.id) {
                "children" in item
                  ? item.children.push(item1)
                  : (item.children = [item1]);
                getTreeData([item1], children);
              }
            });
          });
        }
        getTreeData(parent, children);
        tree.children = parent;
        this.treeList = [tree];
        this.treeList = JSON.parse(JSON.stringify(this.treeList));
      });
    },
    treeSearch(data) {
      this.query.crmclassification = data.id == -1 ? "" : data.id;

      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatortime",
      };
      this.initData();
    },
    ImportPreviewApi(val) {
      let query = { fileName: val };
      request({
        url: `/api/courseinformation/Xy_ks_curriculum_first/ImportPreview`,
        method: "get",
        data: query,
      })
        .then((res) => {
          this.$refs.importBox.list = res.data.dataRow;
          this.$refs.importBox.btnLoading = false;
          this.$refs.importBox.active++;
        })
        .catch(() => {
          this.$refs.importBox.btnLoading = false;
        });
    },
    importDataApi(val) {
      let query = { list: val ,organizeId:this.$store.getters.organizeId};
      request({
        url: `/api/courseinformation/Xy_ks_curriculum_first/ImportData`,
        method: "post",
        data: query,
      })
        .then((res) => {
          this.$refs.importBox.result = res.data;
          this.$refs.importBox.resultList = res.data.failResult;
          this.$refs.importBox.btnLoading = false;
          this.$refs.importBox.active++;
        })
        .catch(() => {
          this.$refs.importBox.btnLoading = false;
        });
    },
    TemplateDownload() {
      request({
        url: `/api/courseinformation/Xy_ks_curriculum_first/templateDownload?organizeId=${this.$store.getters.organizeId}`,
        method: "post",
      }).then((res) => {
        if (!res.data.url) return;
        window.location.href = this.define.comUrl + res.data.url;
      });
    },
    uploadForm() {
      this.importBoxVisible = true;
      this.$nextTick(() => {
        this.$refs.importBox.init(this.columnList);
      });
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == "ascending" ? "asc" : "desc";
      this.listQuery.sidx = !order ? "" : prop;
      this.initData();
    },
    initData() {
      //   this.listLoading = true;
      let _query = {
        ...this.listQuery,
        ...this.query,
        organizeId: this.$store.getters.organizeId,
      };
      let query = {};
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join();
        } else {
          query[key] = _query[key];
        }
      }
      request({
        url: `/api/courseinformation/Xy_ks_curriculum_first`,
        method: "get",
        data: query,
      }).then((res) => {
        this.list = res.data.list;

        this.total = res.data.pagination.total;
        this.listLoading = false;
      });
    },
    handleDel(id) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        type: "warning",
      })
        .then(() => {
          request({
            url: `/api/courseinformation/Xy_ks_curriculum_first/${id}`,
            method: "DELETE",
          }).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },
    handleSelectionChange(val) {
      const res = val.map((item) => item.id);
      this.multipleSelection = res;
    },
    handleBatchRemoveDel() {
      if (!this.multipleSelection.length) {
        this.$message({
          type: "error",
          message: "请选择一条数据",
          duration: 1500,
        });
        return;
      }
      const ids = this.multipleSelection.join();
      this.$confirm("您确定要删除这些数据吗, 是否继续？", "提示", {
        type: "warning",
      })
        .then(() => {
          request({
            url: `/api/courseinformation/Xy_ks_curriculum_first/batchRemove/${ids}`,
            method: "DELETE",
          }).then((res) => {
            this.$message({
              type: "success",
              message: res.msg,
              onClose: () => {
                this.initData();
              },
            });
          });
        })
        .catch(() => {});
    },
    addOrUpdateHandle(id, isDetail, bool) {
      this.formVisible = true;
      this.$nextTick(() => {
        this.$refs.JADPForm.init(id, isDetail, bool);
      });
    },
    practice(id) {
      this.practiceVisible = true;
      this.$nextTick(() => {
        this.$refs.Practice.courseid = id;
        this.$refs.Practice.initData();
      });
    },
    exportData() {
      this.exportBoxVisible = true;
      this.$nextTick(() => {
        this.$refs.ExportBox.init(this.columnList);
      });
    },
    download(data) {
      let query = { ...data, ...this.listQuery, ...this.query };
      request({
        url: `/api/courseinformation/Xy_ks_curriculum_first/Actions/Export`,
        method: "GET",
        data: query,
      }).then((res) => {
        if (!res.data.url) return;
        window.location.href = this.define.comUrl + res.data.url;
        this.$refs.ExportBox.visible = false;
        this.exportBoxVisible = false;
      });
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "",
      };
      this.initData();
    },
    refresh(isrRefresh) {
      this.formVisible = false;
      this.practiceVisible = false;
      this.evaluationVisible = false;
      if (isrRefresh) this.reset();
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined;
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "",
      };
      this.initData();
    },
    bmRecord(command) {
      if (command.name == "a") {
        this.addOrUpdateHandle(command.id, undefined, true);
      }
      if (command.name == "b") {
        this.evaluationVisible = true;
        this.$nextTick(() => {
          this.$refs.Evaluation.coursemanageid = command.id;
          if (command.manageid) {
            this.$refs.Evaluation.manageid = command.manageid;
          }
          this.$refs.Evaluation.initData();
        });
      }
      if (command.name == "c") {
        this.handleDel(command.id);
      }
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .handle-tree {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding-right: 60px;
  box-sizing: border-box;
  align-items: center;
  .btns {
    display: inline-block;
    width: 20px;
  }
}
.content {
  height: 650px;
  display: flex;
  .tree {
    .tree-content {
      padding-bottom: 300px;
      width: 95%;
      margin: 0 auto;
      border: 1px solid rgb(235, 238, 248);

      p {
        line-height: 40px;
        font-size: 20px;
        border-bottom: 1px solid rgb(235, 238, 248);
        text-indent: 10px;
        margin-bottom: 30px;
      }
      ::v-deep .add-input {
        width: 200px;
        line-height: 30px;
        z-index: 50;
        .el-input__inner {
          height: 25px !important;
        }
      }
    }
  }
}
::v-deep .el-dropdown {
  font-size: 12px;
  cursor: pointer;
  margin-top: 0;
  color: #1890ff;
  &:active {
    color: #347abd;
  }
}
::v-deep .el-dropdown-menu--small ::v-deep.el-dropdown-menu__item {
  padding: 0 !important;
}
</style>
